﻿using CommandProcessor.Dispatcher;
using Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using AutoMapper;
using QuanLySanXuat.Models;
using Domain.Commands;
using Core.Common;
using Core.Extensions;
using Data.Models;

namespace QuanLySanXuat.Controllers
{
    public class BillDetailController : Controller
    {
        private readonly ICommandBus commandBus;
        private readonly IBillOutRepository billOutRepository;
        private readonly IStockRepository stockRepository;
        private readonly IEmployeeRepository employeeRepository;
        private readonly IUOMRepository umoRepository;
        private readonly IMaterialRepository materialRepository;
        private readonly IMaterialTypeRepository materialTypeRepository;
        private readonly IPurchaseDetailRepository purchaseRepository;
        //
        // GET: /Bill/
        public BillDetailController(ICommandBus commandBus, IBillOutRepository billOutRepository, IStockRepository stockRepository, IEmployeeRepository employeeRepository, IUOMRepository umoRepository, IMaterialRepository materialRepository, IPurchaseDetailRepository purchaseRepository, IMaterialTypeRepository materialTypeRepository)
        {
            this.commandBus = commandBus;
            this.billOutRepository = billOutRepository;
            this.stockRepository = stockRepository;
            this.employeeRepository = employeeRepository;
            this.umoRepository = umoRepository;
            this.materialRepository = materialRepository;
            this.purchaseRepository = purchaseRepository;
            this.materialTypeRepository = materialTypeRepository;
        }
        public ActionResult Index()
        {
            var billOut = billOutRepository.GetAll();
            return View(billOut.ToPagedList(1, 10));
            
        }
        public ActionResult Create(int? ID)
        {
            ViewData["Stock"] = stockRepository.GetAll();
            ViewData["UOM"] = umoRepository.GetAll();
            ViewData["Employee"] = employeeRepository.GetAll();
            ViewData["Material"] = materialRepository.GetAll();
            ViewData["Purchase"] = purchaseRepository.GetAll();
            var billDetail = billOutRepository.GetById(ID??0);
            var billForm = Mapper.Map<BillOut, BillOutFormModels>(billDetail);
            return View(billForm);
        }
        public ActionResult Save(BillOutFormModels frm)
        {
            var form = new BillOutFormModels()
            {
                ID = frm.ID,
                Code = frm.Code,
                Description = frm.Description,
                TotalMoney=frm.TotalMoney,
                User1ID=frm.User1ID,
                User2ID=frm.User2ID,
                Date1=frm.Date1,
                Date2=frm.Date2,
                WarehouseID=frm.WarehouseID,

            };
            var command = Mapper.Map<BillOutFormModels, CreateOrUpdateBillOutCommand>(form);
            IEnumerable<ValidationResult> errors = commandBus.Validate(command);
            ModelState.AddModelErrors(errors);
            var result = commandBus.Submit(command);

            //Them chi tiet phieu xuat
            if (frm.BillDetailID != null)
            {
                var lst = new List<CreateOrUpdateBillDetailCommand>();
                for (int i = 0; i < frm.BillDetailID.Length; i++)
                {
                    var frmDetail = new BillDetailFormModels()
                    {
                        ID=frm.BillDetailID[i],
                        PurchaseDetailID = frm.PurchaseDetailID[i]??1,
                        Maintenancecost = frm.Maintenancecost[i],
                        MaterialID = frm.MaterialID[i],
                        Price_In = frm.Price_In[i],
                        Price_Out = frm.Price_Out[i],
                        Quantity = frm.Quantity[i],
                        TotalMoney = frm.BillDetailsTotalMoney[i],
                        UOMID = frm.UOMID[i],
                        BillOutID=result.ID,

                    };
                    var cmdMater = Mapper.Map<BillDetailFormModels, CreateOrUpdateBillDetailCommand>(frmDetail);
                    lst.Add(cmdMater);
                }
                commandBus.SubmitRange(lst);
            }

            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult RemoveItems(string[] ProID)
        {
            List<DeleteBillOutCommand> list = new List<DeleteBillOutCommand>();
            foreach (var item in ProID)
            {
                var command = new DeleteBillOutCommand { ID = Convert.ToInt16(item) };
                list.Add(command);
            }
            var result = commandBus.SubmitRange(list);
            var model = billOutRepository.GetAll();
            return PartialView("_BillOutList", model.ToPagedList(1, 10));
        }
        [HttpGet]
        public JsonResult GetUOM(int Code, string Name)
        {
            int uomID = 0;
            uomID = materialTypeRepository.GetById(materialRepository.GetById(Code).MaterialTypeID).UOMID??0;
            return Json(uomID, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        [ValidateInput(false)]
        public ActionResult Page(int PageID)
        {
            var oder = billOutRepository.GetAll().OrderBy(x => x.Code);
            return PartialView("_BillOutList", oder.ToPagedList(1, PageID));
        }
        [HttpGet]
        public ActionResult Search(string Name)
        {
            IEnumerable<BillOut> model;
            if (String.IsNullOrEmpty(Name))
            {
                model = billOutRepository.GetAll();
            }
            else
            {
                model = billOutRepository.GetMany(x => (x.Code.Contains(Name)) || (x.Employee.Name.Contains(Name)));

            }
            return PartialView("_BillOutList", model.ToPagedList(1, 10));
        }
    }
}
